<template>
  <div class="page-coach-list">
    <el-card>
      <el-row
        align="end"
        class="page-coach-list-search"
        justify="space-between"
        type="flex"
      >
        <el-col :span="22">
          <el-form ref="formInline" :inline="true" :model="formInline">
            <el-form-item label="教练姓名: ">
              <el-input
                v-model="formInline.userName"
                placeholder="请输入关键字"
              />
            </el-form-item>
            <el-form-item label="教练账号: ">
              <el-input
                v-model="formInline.nickName"
                placeholder="请输入教练账号"
              />
            </el-form-item>
            <el-form-item label="性别: ">
              <el-select
                v-model="formInline.sex"
                placeholder="全部"
                @change="getCoachData"
              >
                <el-option
                  v-for="item in sexList"
                  :key="item.label"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                icon="el-icon-search"
                type="primary"
                @click="submitForm(formInline)"
              >查找
              </el-button>
              <el-button @click="resetForm(formInline)">清空</el-button>
              <el-button
                :loading="allDownloading"
                icon="el-icon-download"
                @click="clickOnExport"
              >
                导出全部
              </el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="2" style="text-align: right">
          <el-button
            icon="el-icon-plus"
            type="primary"
            @click="handleAddModal"
          >新增
          </el-button>
        </el-col>
      </el-row>

      <!--        .slice((currentPage-1)*pageSize, currentPage*pageSize)-->
      <el-table
        v-loading="loading"
        :cell-style="{ textAlign: 'center' }"
        :data="tableData"
        :header-cell-style="{ textAlign: 'center' }"
        height="70vh"
        highlight-current-row
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          fixed="left"
          label="教练姓名"
          prop="userName"
          width="100"
        />
        <el-table-column label="性别" prop="sex">
          <template slot-scope="scope">
            <span v-if="scope.row.sex === 1">男</span>
            <span v-if="scope.row.sex === 2">女</span>
          </template>
        </el-table-column>
        <!--        <el-table-column label="教练账号" prop="nickName" />-->
        <el-table-column label="所在单位" prop="unitName" width="200" />
        <el-table-column label="诊疗中/人" prop="patientCount" width="100">
          <template slot-scope="scope">
            <el-link
              type="primary"
              @click="clickOnPatientCount(scope.row)"
            >{{ scope.row.patientCount }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="可约时间" prop="configList">
          <el-table-column label="周日" prop="sunday" width="150">
            <template slot-scope="scope">
              <div
                v-if="scope.row.weekList[6].length > 0"
                class="config-week-list"
              >
                <div
                  v-for="(item, index) in scope.row.weekList[6]"
                  :key="`week-6-item-${index}`"
                >
                  <span>{{ item.startTime }} - {{ item.endTime }}</span>
                </div>
              </div>

              <span v-else>/</span>
            </template>
          </el-table-column>
          <el-table-column label="周一" prop="monday" width="150">
            <template slot-scope="scope">
              <div
                v-if="scope.row.weekList[0].length > 0"
                class="config-week-list"
              >
                <div
                  v-for="(item, index) in scope.row.weekList[0]"
                  :key="`week-0-item-${index}`"
                >
                  <span>{{ item.startTime }} - {{ item.endTime }}</span>
                </div>
              </div>

              <span v-else>/</span>
            </template>
          </el-table-column>
          <el-table-column label="周二" prop="tuesday" width="150">
            <template slot-scope="scope">
              <div
                v-if="scope.row.weekList[1].length > 0"
                class="config-week-list"
              >
                <div
                  v-for="(item, index) in scope.row.weekList[1]"
                  :key="`week-1-item-${index}`"
                >
                  <span>{{ item.startTime }} - {{ item.endTime }}</span>
                </div>
              </div>

              <span v-else>/</span>
            </template>
          </el-table-column>
          <el-table-column label="周三" prop="wednesday" width="150">
            <template slot-scope="scope">
              <div
                v-if="scope.row.weekList[2].length > 0"
                class="config-week-list"
              >
                <div
                  v-for="(item, index) in scope.row.weekList[2]"
                  :key="`week-2-item-${index}`"
                >
                  <span>{{ item.startTime }} - {{ item.endTime }}</span>
                </div>
              </div>

              <span v-else>/</span>
            </template>
          </el-table-column>
          <el-table-column label="周四" prop="thursday" width="150">
            <template slot-scope="scope">
              <div
                v-if="scope.row.weekList[3].length > 0"
                class="config-week-list"
              >
                <div
                  v-for="(item, index) in scope.row.weekList[3]"
                  :key="`week-3-item-${index}`"
                >
                  <span>{{ item.startTime }} - {{ item.endTime }}</span>
                </div>
              </div>

              <span v-else>/</span>
            </template>
          </el-table-column>
          <el-table-column label="周五" prop="friday" width="150">
            <template slot-scope="scope">
              <div
                v-if="scope.row.weekList[4].length > 0"
                class="config-week-list"
              >
                <div
                  v-for="(item, index) in scope.row.weekList[4]"
                  :key="`week-4-item-${index}`"
                >
                  <span>{{ item.startTime }} - {{ item.endTime }}</span>
                </div>
              </div>

              <span v-else>/</span>
            </template>
          </el-table-column>
          <el-table-column label="周六" prop="saturday" width="150">
            <template slot-scope="scope">
              <div
                v-if="scope.row.weekList[5].length > 0"
                class="config-week-list"
              >
                <div
                  v-for="(item, index) in scope.row.weekList[5]"
                  :key="`week-5-item-${index}`"
                >
                  <span>{{ item.startTime }} - {{ item.endTime }}</span>
                </div>
              </div>

              <span v-else>/</span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="210">
          <template #default="scope">
            <el-button
              icon="el-icon-edit"
              plain
              size="small"
              type="primary"
              @click.prevent="handleEditModal(scope.row)"
            >编辑
            </el-button>
            <el-button
              icon="el-icon-s-operation"
              plain
              size="small"
              type="danger"
              @click.prevent="clickOnResetPwd(scope.row)"
            >重制密码
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-row class="page-coach-list-pagination">
        <el-col>
          <el-button
            v-if="currentChoose && currentChoose.length > 0"
            :loading="downloading"
            icon="el-icon-download"
            @click="clickOnExportSelection()"
          >导出选中数据
          </el-button>
        </el-col>
        <el-col>
          <pagination
            v-show="total > 0"
            :background="false"
            :limit.sync="pageSize"
            :page.sync="currentPage"
            :total="total"
            @pagination="getCoachData"
          />
        </el-col>

        <!--        <pagination v-show="total>0" :total="total" :page.sync="currentPage" :background="false" :limit.sync="pageSize" @pagination="getCoachData" />-->
      </el-row>
    </el-card>

    <coach-edit-dialog
      v-if="editDialogShown"
      ref="editDialog"
      @closed="editDialogShown = false"
      @updated="getCoachData"
    />

    <coach-reset-pwd-dialog
      v-if="resetPwdDialogShown"
      ref="resetPwdDialog"
      @closed="resetPwdDialogShown = false"
    />
  </div>
</template>

<script>
import { ExportCoaches, GetCoachList } from '@/api/api'

import Pagination from '@/components/Pagination'
import CoachResetPwdDialog from '@/views/coach-list/component/coachResetPwdDialog'
import CoachEditDialog from '@/views/coach-list/component/coachEditDialog'

const sexList = [
  {
    label: '全部',
    value: 0
  },
  {
    label: '男',
    value: '1'
  },
  {
    label: '女',
    value: '2'
  }
]
const processingStatus = [
  {
    label: '已处理',
    value: '1'
  },
  {
    label: '未处理',
    value: '0'
  }
]
const currentStage = [
  {
    label: '未开始',
    value: '未开始'
  },
  {
    label: '初评',
    value: 'S0'
  },
  {
    label: 'Session1',
    value: 'S1'
  },
  {
    label: 'Session2',
    value: 'S2'
  },
  {
    label: 'Session3',
    value: 'S3'
  },
  {
    label: 'Session4',
    value: 'S4'
  },
  {
    label: 'Session5',
    value: 'S5'
  },
  {
    label: 'Session6',
    value: 'S6'
  },
  {
    label: 'Session7',
    value: 'S7'
  },
  {
    label: 'Done',
    value: 'Done'
  }
]

const WeekMapping = {
  周一: 0,
  周二: 1,
  周三: 2,
  周四: 3,
  周五: 4,
  周六: 5,
  周日: 6
}

export default {
  name: 'CoachList',
  components: { CoachEditDialog, CoachResetPwdDialog, Pagination },
  data() {
    return {
      downloading: false,
      allDownloading: false,
      total: 0,
      pageSize: 10,
      currentPage: 0,
      tableData: [],
      formInline: {
        nickName: '',
        userName: '',
        sex: '',
        unitName: ''
      },
      formInDialog: {
        nickName: '',
        userName: '',
        sex: '',
        unitName: ''
      },
      loading: false,

      sexList: sexList,
      processingStatus: processingStatus,
      currentStage: currentStage,
      editDialogShown: false,
      dialogVisible: false,
      currentChooseReset: [],
      currentChooseEdit: [],

      currentChoose: [],
      resetPwdDialogShown: false
    }
  },
  mounted() {
    this.getCoachData(this.formInline)
  },
  methods: {
    reload() {
      this.currentPage = 1
      this.tableData = []
      this.total = 0
      this.getCoachData()
    },
    clickOnPatientCount(item) {
      this.$router.push(
        `/patient-list/index?coach=${
          item.nickName ? item.nickName : item.userName
        }`
      )
    },
    // 获取教练列表
    async getCoachData() {
      const params = {
        ...this.formInline,
        sex: this.formInline.sex === 0 ? undefined : this.formInline.sex
      }

      try {
        if (this.loading) {
          return
        }
        this.loading = true

        const { data } = await GetCoachList({
          ...params,
          pageNum: this.currentPage,
          pageSize: this.pageSize
        })

        const { rows, total, code, msg } = data
        this.loading = false

        if (code !== 200) {
          this.$message.error(msg)
          return
        }
        this.total = total
        this.tableData = rows.map((item) => {
          item.weekList = this.handleCoachConfigList(item.configList)
          return item
        })
      } catch (e) {
        this.loading = false
        console.error(e)
      }
    },

    handleCoachConfigList(configList) {
      if (!configList || configList.length < 0) {
        return
      }
      const weeks = Array.from(Array(7), (item) => [])
      configList.forEach((item) => {
        if (!item.week) {
          return
        }
        const idx = WeekMapping[item.week]
        weeks[idx].push(item)
      })
      return weeks
    },
    submitForm(formEl) {
      if (!formEl) return
      this.getCoachData(formEl)
    },
    resetForm(formEl) {
      if (!formEl) return
      this.formInline = {
        nickName: '',
        userName: '',
        sex: '',
        unitName: ''
      }
    },
    clickOnExport() {
      this.requestExportAll()
    },
    clickOnExportSelection() {
      this.requestExportCoach(
        this.currentChoose.map((item) => {
          return item.userId
        })
      )
    },

    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.reload()
    },
    handlePageCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.reload()
    },

    openEditDialog(adding, form) {
      // console.log(form)
      this.editDialogShown = true
      this.$nextTick(() => {
        this.$refs.editDialog.visiable = true
        this.$refs.editDialog.adding = adding
        if (form) {
          this.$refs.editDialog.updateForm(form)
        }
      })
    },
    handleAddModal() {
      this.openEditDialog(true)
    },
    handleEditModal(row) {
      this.openEditDialog(false, row)
    },
    handleSelectionChange(row) {
      this.currentChoose = row
      // this.currentChoose.push(row)
    },

    clickOnResetPwd(currentChooseReset) {
      this.resetPwdDialogShown = true
      this.$nextTick(() => {
        this.$refs.resetPwdDialog.visiable = true
        this.$refs.resetPwdDialog.form.userId = currentChooseReset.userId
      })
      // this.requestResetPwd(currentChooseReset);
    },
    // async requestExportAll() {
    //   await ExportCoaches()
    // },
    // async requestExportPartial(ids) {
    //   await ExportCoaches({ ids: ids })
    // }

    async requestExportAll() {
      if (this.allDownloading) {
        return
      }
      this.allDownloading = true
      await ExportCoaches()
      this.allDownloading = false
    },
    async requestExportCoach(ids) {
      if (this.downloading) {
        return
      }
      this.downloading = true
      // console.log(ids, ids.join(','))
      await ExportCoaches({ ids: ids })
      this.downloading = false
    }
  }
}
</script>

<style lang="scss" scoped>
.page-coach-list {
  padding: 20px;
  min-height: 80vh;
  background-color: #f9f9f9;

  &-search {
  }

  &-handle {
    margin: 0 0 30px 0;
  }

  &-pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
